package com.fingard.dsp.bank.directbank.pab01;

import java.io.File;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.dsp.bankset.BankFront;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class DownloadFile extends PAB01Base {

    public DownloadFile(ReqRespHeader pHeader, BankFront pBankFront, StringBuilder pSbLog) {
        this.bankFront = pBankFront;
        this.reqHeader = pHeader;
        this.setSbLog(pSbLog);
    }

    public DownFileResp downFile(DownFileReq req) throws Exception {
        DownFileResp resp = new DownFileResp();
        String downloadPath = getBankConfig().getValueAsString("receiptFileDownloadPath");
        //通过共享目录的方式将银行前置下载的回单文件保存到DSP所在服务器的目录
        if (StringHelper.isNullOrEmpty(downloadPath)) {
            downloadPath = req.filePath;
            WriteBankLogLn("银行前置将回单文件下载至DSP所在服务器的目录" + req.filePath);
        } else {
            //挂载共享目录的方式，
            if (!"smb".startsWith(downloadPath)) {
                downloadPath = downloadPath + File.separator + Format.Date6YearMonth.format(new Date()) + File.separator + Format.DateMonth2.format(new Date()) + File.separator + "PAB01";
                WriteBankLogLn("银行前置通过挂载文件夹方式回单文件下载至config.xml文件中<receiptFileDownloadPath>设置的共享目录" + downloadPath);
            } else {
                WriteBankLogLn("银行前置将回单文件下载至config.xml文件中<receiptFileDownloadPath>设置的共享目录" + downloadPath);
            }
        }
        PAB01Header bankHeader = new PAB01Header();
        bankHeader.trncode = "FILE03";//文件下载
        bankHeader.fourZero = "0000";
        bankHeader.reqSeqNo = getQryTransID();
        XmlTextWriter xmlWriter = new XmlTextWriter();
        xmlWriter.autoFormat = false;
        writeCommonHeader(xmlWriter);
        xmlWriter.writeStartElement("Result");
        xmlWriter.writeElementString("TradeSn", bankHeader.reqSeqNo);
        xmlWriter.writeElementString("FileName", req.fileName);
        xmlWriter.writeElementString("FilePath", downloadPath);
        xmlWriter.writeElementString("RandomPwd", req.randomPwd);
        xmlWriter.writeElementString("SignData", req.signData);
        xmlWriter.writeElementString("HashData", req.hashData);
        xmlWriter.writeEndDocument();
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);
        if (tmpStrRet[0].length() == 0 && StringHelper.hasAnyChar(tmpStrRet[1])) {
            String retCode = tmpStrRet[2];
            if ("000000".equals(retCode)) {
                for (int i = 0; i < 500; i++) {//查询文件进度，20次
                    String[] qryResult = qryDownProgress(bankHeader.reqSeqNo);
                    if ("0".equals(qryResult[0])) {
                        resp.execResult = true;
                        if (!StringHelper.isNullOrEmpty(downloadPath)) {
                            //通过共享目录下载到本地DSP
                            if ("smb".startsWith(downloadPath)) {
                                StringBuilder sb = new StringBuilder();
                                if (!saveReceiptToDSP(downloadPath, req.filePath, sb, req.fileName)) {
                                    resp.execResult = false;
                                    resp.execMsg = "从银行前置机下载的回单目录保存文件到本地DSP贡献目录失败，失败原因为" + sb.toString();
                                }
                            } else {
                                //通过挂载目录的方式下载到本地DSP
                                String mountFolderPath = getBankConfig().getValueAsString("mountFolderPath");
                                if (!StringHelper.isNullOrEmpty("mountFolderPath")) {
                                    mountFolderPath = mountFolderPath + File.separator + Format.Date6YearMonth.format(new Date()) + File.separator + Format.DateMonth2.format(new Date()) + File.separator + "PAB01";
                                    int copyResult = FileHelper.copyFile(mountFolderPath + File.separator + req.fileName, req.filePath + File.separator + req.fileName);
                                    if (1 == copyResult){
                                        resp.execResult = false;
                                        resp.execMsg = "文件已经下载至本地目录，无需重复下载";
                                        return resp;
                                    }
                                } else {
                                    resp.execResult = false;
                                    resp.execMsg = "mountFolderPath节点不得为空";
                                    return resp;
                                }
                            }
                        }
                        return resp;
                    } else {
                        resp.execResult = false;
                        resp.execMsg = qryResult[1];
                        if (StringHelper.hasAnyChar(req.filePath)) {
                            resp.resultFilePath = StringHelper.trimEndFileSp(req.filePath) + File.separator + req.fileName;
                        } else {
                            resp.resultFilePath = req.fileName;
                        }
                    }
                    Thread.sleep(1000);
                }
            } else {
                resp.execResult = false;
                resp.execMsg = tmpStrRet[3];
            }
        } else {
            resp.execResult = false;
            resp.execMsg = StringHelper.joinNotEmpty("-", tmpStrRet);
        }
        return resp;
    }

    /**
     * @param downloadPath 共享目录地址
     * @param filePath     本机目录
     * @param sb           错误信息
     * @param fileName     文件名
     * @return
     */
    private boolean saveReceiptToDSP(String downloadPath, String filePath, StringBuilder sb, String fileName) {
        try {
            int i = SmbFileUtil.smbDownload(filePath, downloadPath, fileName, sb);
            if (1 == i) return true;
        } catch (Exception e) {
            WriteBankLogLn("从远程目录下载文件发生异常，异常信息为：" + e.getMessage());
        }
        return false;
    }

    /**
     * 查询文件下载进度
     *
     * @throws Exception
     */
    public String[] qryDownProgress(String pTradeSn) throws Exception {
        String[] retVal = new String[]{"", ""};

        PAB01Header bankHeader = new PAB01Header();
        bankHeader.trncode = "FILE02";
        bankHeader.fourZero = "0000";
        bankHeader.reqSeqNo = getQryTransID();
        XmlTextWriter xmlWriter = new XmlTextWriter();
        xmlWriter.autoFormat = false;
        writeCommonHeader(xmlWriter);
        xmlWriter.writeStartElement("Result");
        xmlWriter.writeElementString("TradeSn", pTradeSn);
        xmlWriter.writeEndDocument();

        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);
        if (tmpStrRet[0].length() == 0 && StringHelper.hasAnyChar(tmpStrRet[1])) {
            String retCode = tmpStrRet[2];
            if ("000000".equals(retCode)) {
                if (tmpStrRet[1].contains("<")) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);

                    if (tmpBkReader != null) {
                        String downCode = tmpBkReader.getFirstText("/Result/Code");
                        if ("F0".equals(downCode)) {
                            retVal[0] = "0";//下载完成
                        }
                    } else {
                        retVal[1] = tmpSbMsg.toString();
                    }
                } else {
                    retVal[1] = tmpStrRet[1];
                }
            } else {
                retVal[1] = tmpStrRet[3];
            }
        } else {
            retVal[1] = StringHelper.joinNotEmpty("-", tmpStrRet);
        }
        return retVal;
    }
}
